import { knowledgeApi } from '@/utils/api'

/**
 * 知识库 Vuex 模块
 */
const state = {
  // 知识库列表
  knowledgeList: [],
  // 当前选中的知识库
  currentKnowledge: null,
  // 加载状态
  loading: false
}

const getters = {
  /**
   * 获取知识库列表
   * @param {Object} state - Vuex状态
   * @returns {Array} 知识库列表
   */
  getKnowledgeList: state => state.knowledgeList,
  
  /**
   * 获取当前选中的知识库
   * @param {Object} state - Vuex状态
   * @returns {Object} 当前选中的知识库
   */
  getCurrentKnowledge: state => state.currentKnowledge,
  
  /**
   * 获取加载状态
   * @param {Object} state - Vuex状态
   * @returns {Boolean} 加载状态
   */
  getLoading: state => state.loading
}

const mutations = {
  /**
   * 设置知识库列表
   * @param {Object} state - Vuex状态
   * @param {Array} list - 知识库列表
   */
  SET_KNOWLEDGE_LIST(state, list) {
    state.knowledgeList = list
  },
  
  /**
   * 设置当前选中的知识库
   * @param {Object} state - Vuex状态
   * @param {Object} knowledge - 知识库对象
   */
  SET_CURRENT_KNOWLEDGE(state, knowledge) {
    state.currentKnowledge = knowledge
  },
  
  /**
   * 添加知识库
   * @param {Object} state - Vuex状态
   * @param {Object} knowledge - 知识库对象
   */
  ADD_KNOWLEDGE(state, knowledge) {
    state.knowledgeList.unshift(knowledge)
  },
  
  /**
   * 更新知识库
   * @param {Object} state - Vuex状态
   * @param {Object} knowledge - 更新的知识库对象
   */
  UPDATE_KNOWLEDGE(state, knowledge) {
    const index = state.knowledgeList.findIndex(k => k.id === knowledge.id)
    if (index !== -1) {
      state.knowledgeList.splice(index, 1, {
        ...state.knowledgeList[index],
        ...knowledge
      })
      
      // 如果当前选中的知识库是被更新的知识库，也更新当前选中的知识库
      if (state.currentKnowledge && state.currentKnowledge.id === knowledge.id) {
        state.currentKnowledge = {
          ...state.currentKnowledge,
          ...knowledge
        }
      }
    }
  },
  
  /**
   * 删除知识库
   * @param {Object} state - Vuex状态
   * @param {Number} id - 知识库ID
   */
  DELETE_KNOWLEDGE(state, id) {
    const index = state.knowledgeList.findIndex(k => k.id === id)
    if (index !== -1) {
      state.knowledgeList.splice(index, 1)
    }
    
    // 如果当前选中的知识库是被删除的知识库，清空当前选中的知识库
    if (state.currentKnowledge && state.currentKnowledge.id === id) {
      state.currentKnowledge = null
    }
  },
  
  /**
   * 设置加载状态
   * @param {Object} state - Vuex状态
   * @param {Boolean} loading - 加载状态
   */
  SET_LOADING(state, loading) {
    state.loading = loading
  }
}

const actions = {
  /**
   * 获取知识库列表
   * @param {Object} context - Vuex上下文
   */
  async fetchKnowledgeList({ commit }) {
    commit('SET_LOADING', true)
    try {
      const response = await knowledgeApi.getList()
      if (response.success) {
        commit('SET_KNOWLEDGE_LIST', response.data)
      } else {
        console.error('获取知识库列表失败:', response.message)
      }
    } catch (error) {
      console.error('获取知识库列表错误:', error)
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  /**
   * 搜索知识库
   * @param {Object} context - Vuex上下文
   * @param {String} name - 知识库名称（模糊搜索）
   */
  async searchKnowledge({ commit }, name) {
    commit('SET_LOADING', true)
    try {
      const response = await knowledgeApi.search(name)
      if (response.success) {
        commit('SET_KNOWLEDGE_LIST', response.data)
      } else {
        console.error('搜索知识库失败:', response.message)
      }
    } catch (error) {
      console.error('搜索知识库错误:', error)
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  /**
   * 获取知识库详情
   * @param {Object} context - Vuex上下文
   * @param {Number} id - 知识库ID
   */
  async fetchKnowledgeDetail({ commit }, id) {
    commit('SET_LOADING', true)
    try {
      const response = await knowledgeApi.getDetail(id)
      if (response.success) {
        commit('SET_CURRENT_KNOWLEDGE', response.data)
      } else {
        console.error('获取知识库详情失败:', response.message)
      }
    } catch (error) {
      console.error('获取知识库详情错误:', error)
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  /**
   * 创建知识库
   * @param {Object} context - Vuex上下文
   * @param {Object} knowledge - 知识库对象
   */
  async createKnowledge({ commit }, knowledge) {
    commit('SET_LOADING', true)
    try {
      const response = await knowledgeApi.create(knowledge)
      if (response.success) {
        // 创建成功后，重新获取知识库列表
        const detailResponse = await knowledgeApi.getDetail(response.data.id)
        if (detailResponse.success) {
          commit('ADD_KNOWLEDGE', detailResponse.data)
          return { success: true, data: detailResponse.data }
        }
      } else {
        console.error('创建知识库失败:', response.message)
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('创建知识库错误:', error)
      return { success: false, message: error.message }
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  /**
   * 更新知识库
   * @param {Object} context - Vuex上下文
   * @param {Object} knowledge - 知识库对象
   */
  async updateKnowledge({ commit }, knowledge) {
    commit('SET_LOADING', true)
    try {
      const response = await knowledgeApi.update(knowledge)
      if (response.success) {
        // 更新成功后，重新获取知识库详情
        const detailResponse = await knowledgeApi.getDetail(knowledge.id)
        if (detailResponse.success) {
          commit('UPDATE_KNOWLEDGE', detailResponse.data)
          return { success: true, data: detailResponse.data }
        }
      } else {
        console.error('更新知识库失败:', response.message)
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('更新知识库错误:', error)
      return { success: false, message: error.message }
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  /**
   * 删除知识库
   * @param {Object} context - Vuex上下文
   * @param {Number} id - 知识库ID
   */
  async deleteKnowledge({ commit }, id) {
    commit('SET_LOADING', true)
    try {
      const response = await knowledgeApi.delete(id)
      if (response.success) {
        commit('DELETE_KNOWLEDGE', id)
        return { success: true }
      } else {
        console.error('删除知识库失败:', response.message)
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('删除知识库错误:', error)
      return { success: false, message: error.message }
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  /**
   * 保存知识库Excalidraw画板数据
   * @param {Object} context - Vuex上下文
   * @param {Object} payload - 包含id和excalidraw数据的对象
   */
  async saveKnowledgeExcalidraw({ commit }, { id, excalidraw }) {
    commit('SET_LOADING', true)
    try {
      const response = await knowledgeApi.saveExcalidraw(id, excalidraw)
      if (response.success) {
        // 更新成功后，更新本地知识库数据
        commit('UPDATE_KNOWLEDGE', { id, excalidraw })
        return { success: true, data: response.data }
      } else {
        console.error('保存Excalidraw数据失败:', response.message)
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('保存Excalidraw数据错误:', error)
      return { success: false, message: error.message }
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  /**
   * 上传Excalidraw附件
   * @param {Object} context - Vuex上下文
   * @param {Object} payload - 包含knowledgeId和file的对象
   */
  async uploadExcalidrawAttachment({ commit }, { knowledgeId, file }) {
    commit('SET_LOADING', true)
    try {
      const response = await knowledgeApi.uploadExcalidrawAttachment(knowledgeId, file)
      if (response.success) {
        return { success: true, data: response.data }
      } else {
        console.error('上传Excalidraw附件失败:', response.message)
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('上传Excalidraw附件错误:', error)
      return { success: false, message: error.message }
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  /**
   * 获取Excalidraw附件列表
   * @param {Object} context - Vuex上下文
   * @param {Number} knowledgeId - 知识库ID
   */
  async getExcalidrawAttachments({ commit }, knowledgeId) {
    commit('SET_LOADING', true)
    try {
      const response = await knowledgeApi.getExcalidrawAttachments(knowledgeId)
      if (response.success) {
        return { success: true, data: response.data }
      } else {
        console.error('获取Excalidraw附件列表失败:', response.message)
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('获取Excalidraw附件列表错误:', error)
      return { success: false, message: error.message }
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  /**
   * 删除Excalidraw附件
   * @param {Object} context - Vuex上下文
   * @param {Number} attachmentId - 附件ID
   */
  async deleteExcalidrawAttachment({ commit }, attachmentId) {
    commit('SET_LOADING', true)
    try {
      const response = await knowledgeApi.deleteExcalidrawAttachment(attachmentId)
      if (response.success) {
        return { success: true, data: response.data }
      } else {
        console.error('删除Excalidraw附件失败:', response.message)
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('删除Excalidraw附件错误:', error)
      return { success: false, message: error.message }
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  /**
   * 获取知识库Excalidraw画板数据
   * @param {Object} context - Vuex上下文
   * @param {Number} id - 知识库ID
   */
  async getKnowledgeExcalidraw({ commit }, id) {
    commit('SET_LOADING', true)
    try {
      const response = await knowledgeApi.getExcalidraw(id)
      if (response.success) {
        return { success: true, data: response.data }
      } else {
        console.error('获取Excalidraw数据失败:', response.message)
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('获取Excalidraw数据错误:', error)
      return { success: false, message: error.message }
    } finally {
      commit('SET_LOADING', false)
    }
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}